//
//  SEGTrackRecordView.m
//  Uhomebk
//
//  Created by mac on 2017/10/24.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "SEGTrackRecordView.h"
#import <AVFoundation/AVFoundation.h>
@interface SEGTrackRecordView()<AVAudioPlayerDelegate>
{
    NSOperationQueue *queue;
    AVAudioSession *session;
    NSDictionary *settings;
    NSInteger   timenum;
    UIImageView *playAnimotion;//播放录音动画
    NSTimer *timer;//计时器
    CustomButtonView* playBtn;//点击播放按钮
    AVAudioPlayer *player;
    NSDictionary *_params;
}
@property (nonatomic, strong)   NSMutableArray *soundDataArray;    /**<声音数组*/
@end

@implementation SEGTrackRecordView

-(instancetype)initWithFrame:(CGRect)frame data:(NSDictionary *)dict
{
    if (self = [super initWithFrame:frame]) {
        _params = dict;
        [self initRecordSettingWith:dict];
        self.backgroundColor = kColor_W;

    }

    return self;
}


/**
 初始化播放录音配置
 */
-(void)initRecordSettingWith:(NSDictionary *)dict
{
    UILabel* titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 11+12, 0,20)];
    [titleLabel setText:dict[@"title"]];
    [titleLabel setFont:kFont_15];
    [titleLabel sizeToFit];
    [titleLabel setTextColor:kColor_1];
    titleLabel.tag = 111;
    [self addSubview:titleLabel];
    NSLog(@"titile = %@",NSStringFromCGRect(titleLabel.frame));
    //播放按钮
    playBtn = [[CustomButtonView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(titleLabel.frame)+10, 12, 120, 30)];
    [playBtn setHidden:NO];
    [playBtn setTitle:@"点击播放" forState:UIControlStateNormal];
    [playBtn.titleLabel setFont:kFont_15];
    [playBtn setTitleColor:kColor_1 forState:UIControlStateNormal];
    playBtn.layer.borderColor = kColor_L2.CGColor;
    playBtn.layer.borderWidth = 0.5;
    playBtn.layer.cornerRadius = 4;
    [playBtn.layer setMasksToBounds:YES];
    playBtn.tempData = dict;
    [playBtn addTarget:self action:@selector(onPlayAudioUrl:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:playBtn];
     NSLog(@"playBtn = %@",NSStringFromCGRect(playBtn.frame));
    NSArray* soundArray = @[ [UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_volume_1")], [UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_volume_2")], [UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_volume_3")] ];
    UIImage* tempImage = [soundArray objectAtIndex:0];
    
    playAnimotion = [[UIImageView alloc] initWithFrame:CGRectMake(10, (CGRectGetHeight(playBtn.bounds) - tempImage.size.height) / 2, tempImage.size.width, tempImage.size.height)];
    playAnimotion.animationImages = soundArray;
    playAnimotion.animationRepeatCount = 0;
    playAnimotion.animationDuration = 2.0;
    [playBtn addSubview:playAnimotion];
    
    
    self.height = 42+12;
}

-(void)onPlayAudioUrl:(CustomButtonView *)sender
{
    //暂停播放
    if ([player isPlaying]) {
        [player stop];
        
        AVAudioSession* audioSession = [AVAudioSession sharedInstance];
        NSError* err = nil;
        [audioSession setCategory:AVAudioSessionCategoryRecord error:&err];//播放声音的同时停止其他应用声音
        
        [playBtn setTitle:@"点击播放" forState:UIControlStateNormal];
        
        [playAnimotion stopAnimating];

        return;
    }
    
    
    NSString *attrValue = [_params valueForKey:@"attrValue"];
    
    if (attrValue.length ==  0) {
        [SEGAlertView showTmepMessageWithMessage:@"未找到有效的录音资源"];
        return;
        
    }
    
    NSURL  *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@", [SEGOnefileuploadManager sharedManager].urlString, attrValue]];
    if (url == nil) {
        [SEGAlertView showTmepMessageWithMessage:@"无效的录音文件资源"];
        return;
    }
    NSData* sounddata = [NSData dataWithContentsOfURL:url];
    NSError* playerError;
    
    //播放.wav格式
    
    NSData* tempData = sounddata;
    
    player = nil;
    
    player = [[AVAudioPlayer alloc] initWithData:tempData error:&playerError];
    player.delegate = self;
    if (player == nil) {
        [SEGAlertView showTmepMessageWithMessage:@"读取录音文件失败"];
    }
    else {
        AVAudioSession* audioSession = [AVAudioSession sharedInstance];
        NSError* err = nil;
        [audioSession setCategory:AVAudioSessionCategoryPlayback error:&err];
        if ([player prepareToPlay])
        {
            /**
             *  增加播放声音通知
             */
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopSound) name:@"STOPSOUND" object:nil];
            [player play];
            [sender setTitle:@"      播放中..." forState:UIControlStateNormal];
            [playAnimotion startAnimating];
        }
        else
        {
            [SEGAlertView showTmepMessageWithMessage:@"读取录音文件失败"];
        }
        
    }
}

//录音播放完成回调
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer*)player successfully:(BOOL)flag
{
    if (flag) {
        AVAudioSession* audioSession = [AVAudioSession sharedInstance];
        NSError* err = nil;
        [audioSession setCategory:AVAudioSessionCategoryRecord error:&err];
    }
    
    [playBtn setTitle:@"点击播放" forState:UIControlStateNormal];
    
    [playAnimotion stopAnimating];
    
}


/**
 *  停止播放声音
 */
- (void)stopSound
{
    [player stop];
    player = nil;
    [playBtn setTitle:@"点击播放" forState:UIControlStateNormal];
    [playAnimotion stopAnimating];
}

@end
